import { _decorator, Label, Button, v3, Vec3 } from 'cc';
import { BasePanel } from '../../../../scripts/libs/ui/BasePanel';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { DevConfig } from '../../../../scripts/managers/DevConfig';
import { udm } from '../../../../scripts/managers/UserDataManager';
import { lm } from '../../LobbyManager';
import { MSResolve, MSRToString_th_m_s } from '../../../../scripts/libs/utils/date';
import { IapButtonItem } from '../ShopPanel/IapButtonItem';
import { ProgressBar } from 'cc';
import { Node } from 'cc';
import { find } from 'cc';
import { IntervalStartNow, Timer } from '../../../../scripts/libs/rxjs/cc3/CreatorSchedule';
import { linear } from '../../../../scripts/libs/utils/math';
import { gm } from '../../../../scripts/managers/GameManager';
import { nc } from '../../../../scripts/libs/rxjs/NotificationCenter';
import { concat, forkJoin, Observable } from 'rxjs';
import { TweenToStart } from '../../../../scripts/libs/rxjs/cc3/TweenStart';
const { ccclass, property } = _decorator;

@ccclass('SavingPotPanel')
export class SavingPotPanel extends BasePanel {

    @property(Node)
    mainNode: Node = null;

    @property(Button)
    closeButton: Button = null;

    @property(Button)
    continueButton: Button = null;

    @property(IapButtonItem)
    iapButtonItem: IapButtonItem = null;

    @property(ProgressBar)
    progressData: ProgressBar = null

    @property(Label)
    currentCoin: Label = null

    @property(Node)
    timeNode: Node = null

    @property(Label)
    timeData: Label = null

    @property(Node)
    coin0Node: Node = null;

    @property(Node)
    coin1Node: Node = null;

    @property(Node)
    pigNode: Node = null;

    willBind(): void {
        lm.pausePanelOpened.value = true;
        this.iapButtonItem.data.value = DevConfig.iap.savingpot_0;

        let coin0x = linear(0, 1, -366, 366, DevConfig.SAVING_POT.UNLOCK_COUNT / DevConfig.SAVING_POT.COIN_CAPACITY);
        this.coin0Node.setPosition(coin0x, 0, 0);
        find('Label', this.coin0Node).getComponent(Label).string = `${DevConfig.SAVING_POT.UNLOCK_COUNT}`;

        let coin1x = linear(0, 1, -366, 366, 1);
        this.coin1Node.setPosition(coin1x, 0, 0);
        find('Label', this.coin1Node).getComponent(Label).string = `${DevConfig.SAVING_POT.COIN_CAPACITY}`;
        // this.adaptive();
        this.mainNode.setScale(.5, .5, .5);
    }

    useObserves() {
        return [
            BindButton(this.closeButton).subscribe(this.closeButtonClicked.bind(this)),
            BindButton(this.continueButton).subscribe(this.closeButtonClicked.bind(this)),
            udm.savingPot.subscribe(this.refresh.bind(this)),

            this.iapButtonItem.beforeProvideCommand.subscribe(_ => {
                gm.coinAnimatingFlags.add('iap_coin');
                this._coinValueReward = udm.savingPot.value.coin;
            }),
            this.iapButtonItem.successCommand.subscribe(this.onBuySuccess.bind(this)),

            IntervalStartNow(1, this.node).subscribe(this.refresh.bind(this))
        ];
    }

    // adaptive() {
    //     this.mainNode.setScale(v3(Vec3.ONE).multiplyScalar(lm.getAdaptiveScale()));
    // }

    openPanelAnim(): Observable<any> {
        return forkJoin([
            TweenToStart(this.ensureUIOpacity(), .2, { opacity: 255 }, { easing: 'expoOut' }),
            TweenToStart(this.mainNode, .4, { scale: lm.getAdaptiveScaleV3() }, { easing: 'backOut' }),
        ]);
    }

    closePanelAnim(): Observable<any> {
        this.ensureUIOpacity();
        return forkJoin([
            TweenToStart(this.ensureUIOpacity(), .2, { opacity: 0 }, { easing: 'expoIn' }),
            TweenToStart(this.mainNode, .2, { scale: v3(.5, .5, .5) }, { easing: 'backIn' }),
        ]);
    }

    onDestroyView(): void {
        lm.pausePanelOpened.value = false;
    }

    _coinValueReward = 0;

    refresh() {
        let remainMs = udm.savingPotGetRemainRsToReset();
        if (remainMs != null) {
            this.timeNode.active = true
            let msr = MSResolve(remainMs);
            this.timeData.string = MSRToString_th_m_s(msr)
        }

        if (udm.savingPot.value.coin >= DevConfig.SAVING_POT.UNLOCK_COUNT) {
            this.iapButtonItem.limitReason.delete('unlock_count');
            this.iapButtonItem.node.active = true;
            this.continueButton.node.active = false;
        } else {
            this.iapButtonItem.limitReason.add('unlock_count');
            this.iapButtonItem.node.active = false;
            this.continueButton.node.active = true;
        }
        this.currentCoin.string = udm.savingPot.value.coin ? String(udm.savingPot.value.coin) : '';
        this.progressData.progress = udm.savingPot.value.coin / DevConfig.SAVING_POT.COIN_CAPACITY;

    }

    closeButtonClicked() {
        SavingPotPanel.CloseProcess(null, 'close');
    }

    onBuySuccess() {
        nc.post('fly_coins', { fromWorldPos: this.pigNode.worldPosition, count: this._coinValueReward ?? 0 });
        gm.coinAnimatingFlags.delete('iap_coin');
        SavingPotPanel.CloseProcess(null, 'purchased');
    }

}

